package com.zx.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020-03-12
 */
@Component
public class LoginFilter extends ZuulFilter {


    /**
     * 指定filter类型 pre routing post error
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 指定filter顺序 值越小 filter级别越高
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 指定是否开启此filter
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 真正实现业务处理
     */
    @Override
    public Object run() throws ZuulException {

        // 获取zuul提供的上下文
        RequestContext currentContext = RequestContext.getCurrentContext();
        // 获取request对象
        HttpServletRequest request = currentContext.getRequest();
        // 从request域中获取token
        String token = request.getParameter("access-token");
        // 判断token是否存在
        if (StringUtils.isEmpty(token)){
            // 如果token不存在 拦截
            currentContext.setSendZuulResponse(false);
            // 设置响应状态码 401 也可以考虑重定向到登录页面
            currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }
        // 校验通过
        return null;
    }
}
